<template>
    <div>
        <el-card shadow="never">
            <template slot="header">
                <span>订单管理</span>
            </template>

            <!-- 搜索区域 -->
            <Search :search-options="searchOptions" @search="handleSearch">
                <template slot="extra-buttons">
                    <el-button type="primary" v-auth="'add'" @click="addOrder">新增订单</el-button>
                    <el-button type="primary" v-auth="'batch'" @click="batchHandle">批量操作</el-button>
                    <el-button type="success" v-auth="'export'" @click="exportOrders">导出订单</el-button>
                </template>
            </Search>

            <!-- 订单表格 -->
            <el-table v-loading="listLoading" element-loading-text="数据正在加载中" :data="data" border fit
                highlight-current-row style="width: 100%" @selection-change="handleSelectionChange"
                @sort-change="handleSortChange">

                <el-table-column v-for="item in columns" :key="item.prop" :label="item.label" :prop="item.prop"
                    :align="item.align" :width="item.width">

                    <template slot-scope="{ row , $index}">
                        <!-- 序号 -->
                        <div v-if="item.prop === 'index'">
                            {{ $index + 1 }}
                        </div>
                        <div v-else-if="item.prop === 'materialType'">
                            {{ MATERIAL_TYPE_MAP[row.materialType]?.label || row.materialType }}
                        </div>
                        <!-- 订单类型 -->
                        <div v-else-if="item.prop === 'orderType'">
                            <el-tag :type="ORDER_TYPE_MAP[row.orderType]?.type || 'info'">
                                {{ ORDER_TYPE_MAP[row.orderType]?.label || row.orderType }}
                            </el-tag>
                        </div>

                        <!-- 订单状态 -->
                        <div v-else-if="item.prop === 'orderStatus'">
                            <el-tag :type="ORDER_STATUS_MAP[row.orderStatus]?.type || 'info'">
                                {{ ORDER_STATUS_MAP[row.orderStatus]?.label || row.orderStatus }}
                            </el-tag>
                        </div>

                        <!-- 价格相关字段 -->
                        <div
                            v-else-if="['orderPrice', 'manageFee', 'retainerAmount', 'stopProfitLimit', 'stopLossLimit'].includes(item.prop)">

                          <div v-if="item.prop=='orderPrice'" style="text-align: left">
                              <p v-show="row.orderPrice">下单单价：{{ formatPrice(row.orderPrice) }}</p>
                              <p v-show="row.orderTime">下单时间：{{ formatDateTime(row.orderTime) }}</p>
                          </div>
                          <div v-else>
                            <span class="price-text">¥{{ formatPrice(row[item.prop]) }}</span>
                          </div>
                        </div>

                        <!-- 重量字段 -->
                        <div v-else-if="item.prop === 'weight'">
                            <span>{{ formatWeight(row.weight) }}g</span>
                        </div>

                        <!-- 时间字段 -->
                        <div v-else-if="item.prop === 'orderTime'">
                            <span>{{ formatDateTime(row.orderTime) }}</span>
                        </div>
                      <div v-else-if="item.prop === 'settleTime'">
                          <div v-show="row.settleTime" style="text-align: left">
                            <p >结算单价：{{row.settlePrice}}</p>
                            <p >结算时间：{{ formatDateTime(row.settleTime) }}</p>
                          </div>
                      </div>
                        <!-- 默认显示 -->
                        <div v-else>
                            {{ row[item.prop] || '-' }}
                        </div>
                    </template>
                </el-table-column>

                <!-- 操作列 -->
                <el-table-column label="操作" width="100" align="center" fixed="right">
                    <template slot-scope="{ row }">
                        <el-button type="primary" size="mini" @click="handleView(row)">
                            查看
                        </el-button>
                        <!-- <el-button type="success" size="mini" @click="handleEdit(row)" v-auth="'edit'">
                            编辑
                        </el-button>
                        <el-button type="warning" size="mini" @click="handleStatusChange(row)" v-auth="'status'">
                            状态
                        </el-button>
                        <el-button type="danger" size="mini" @click="handleDel(row)" v-auth="'del'">
                            删除
                        </el-button> -->
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页 -->
            <Pagination :page="current" :page_size="size" :total="total" @sizeChange="sizeChange"
                @currentChange="pageChange" />
        </el-card>

        <!-- 批量操作对话框 -->
        <el-dialog title="批量操作" :visible.sync="showBatch" width="30%" :close-on-click-modal="false">
            <el-form :model="batchForm" label-width="100px">
                <el-form-item label="操作类型">
                    <el-radio-group v-model="batchForm.operationType">
                        <el-radio label="status">修改状态</el-radio>
                        <el-radio label="delete">批量删除</el-radio>
                    </el-radio-group>
                </el-form-item>

                <el-form-item label="订单状态" v-if="batchForm.operationType === 'status'">
                    <el-select v-model="batchForm.status" placeholder="请选择状态">
                        <el-option v-for="(status, key) in ORDER_STATUS_MAP" :key="key" :label="status.label"
                            :value="key" />
                    </el-select>
                </el-form-item>
            </el-form>

            <span slot="footer" class="dialog-footer">
                <el-button @click="showBatch = false">取 消</el-button>
                <el-button type="primary" @click="submitBatch">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 状态修改对话框 -->
        <el-dialog title="修改订单状态" :visible.sync="showStatusDialog" width="30%" :close-on-click-modal="false">
            <el-form :model="statusForm" label-width="100px">
                <el-form-item label="当前状态">
                    <el-tag :type="ORDER_STATUS_MAP[currentOrder?.orderStatus]?.type || 'info'">
                        {{ ORDER_STATUS_MAP[currentOrder?.orderStatus]?.label || currentOrder?.orderStatus }}
                    </el-tag>
                </el-form-item>

                <el-form-item label="新状态">
                    <el-select v-model="statusForm.newStatus" placeholder="请选择新状态">
                        <el-option v-for="(status, key) in ORDER_STATUS_MAP" :key="key" :label="status.label"
                            :value="key" />
                    </el-select>
                </el-form-item>

                <el-form-item label="备注">
                    <el-input v-model="statusForm.remark" type="textarea" :rows="3" placeholder="请输入状态变更备注" />
                </el-form-item>
            </el-form>

            <span slot="footer" class="dialog-footer">
                <el-button @click="showStatusDialog = false">取 消</el-button>
                <el-button type="primary" @click="submitStatusChange">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import Search from '@/components/Search.vue'
import Pagination from '@/components/Pagination.vue'
import { SEARCH_OPTIONS, columns, ORDER_STATUS_MAP, ORDER_TYPE_MAP, MATERIAL_TYPE_MAP } from './options'
import { getOrderList, updateOrderStatus, deleteOrder, batchOperation } from './api/order'

export default {
    name: 'OrderList',
    components: {
        Search,
        Pagination
    },
    data() {
        return {
            // 搜索和表格配置
            searchOptions: SEARCH_OPTIONS,
            MATERIAL_TYPE_MAP,
            columns: columns,
            ORDER_STATUS_MAP,
            ORDER_TYPE_MAP,

            // 数据相关
            listLoading: false,
            data: [],
            current: 1,
            total: 0,
            size: 20,
            searchParams: {},
            selectedIds: [],

            // 对话框相关
            showBatch: false,
            showStatusDialog: false,
            currentOrder: null,

            // 批量操作表单
            batchForm: {
                operationType: 'status',
                status: ''
            },

            // 状态修改表单
            statusForm: {
                newStatus: '',
                remark: ''
            }
        }
    },

    created() {
        this.init()
    },

    methods: {
        // 初始化
        init() {
            this.getList()
        },

        // 获取订单列表
        async getList() {
            this.listLoading = true
            try {
                const params = {
                    current: this.current,
                    size: this.size,
                    ...this.searchParams
                }

                const res = await getOrderList(params)

                this.total = res.total || res.count || 0
                this.data = res.records || res.list || []
            } catch (error) {
                console.error('获取订单列表失败:', error)
                this.$message.error('获取订单列表失败')
            } finally {
                this.listLoading = false
            }
        },

        // 搜索处理
        handleSearch(params) {
            this.searchParams = { ...params }
            this.current = 1
            this.getList()
        },

        // 排序处理
        handleSortChange(sort) {
            if (sort.prop && sort.order) {
                this.searchParams.sortBy = sort.prop
                this.searchParams.sortOrder = sort.order === 'ascending' ? 'asc' : 'desc'
                this.getList()
            }
        },

        // 选择变化
        handleSelectionChange(val) {
            this.selectedIds = val.map(item => item.id)
        },

        // 分页变化
        pageChange(page) {
            this.current = page
            this.getList()
        },

        sizeChange(size) {
            this.size = size
            this.current = 1
            this.getList()
        },

        // 新增订单
        addOrder() {
            this.$router.push('/order/add')
        },

        // 查看订单
        handleView(row) {
            if (!row || !row.id) {
                this.$message.warning('无法获取订单ID')
                return
            }
            this.$router.push(`/order/detail/${row.id}`)
        },

        // 编辑订单
        handleEdit(row) {
            this.$router.push(`/order/edit/${row.id}`)
        },

        // 状态修改
        handleStatusChange(row) {
            this.currentOrder = row
            this.statusForm.newStatus = row.orderStatus
            this.statusForm.remark = ''
            this.showStatusDialog = true
        },

        // 提交状态修改
        async submitStatusChange() {
            if (!this.statusForm.newStatus) {
                this.$message.warning('请选择新状态')
                return
            }

            try {
                await updateOrderStatus({
                    id: this.currentOrder.id,
                    status: this.statusForm.newStatus,
                    remark: this.statusForm.remark
                })

                this.$message.success('状态修改成功')
                this.showStatusDialog = false
                this.getList()
            } catch (error) {
                console.error('状态修改失败:', error)
                this.$message.error('状态修改失败')
            }
        },

        // 删除订单
        handleDel(row) {
            this.$confirm('确认删除该订单?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                try {
                    await deleteOrder([row.id])
                    this.$message.success('删除成功!')
                    this.getList()
                } catch (error) {
                    console.error('删除失败:', error)
                    this.$message.error('删除失败')
                }
            }).catch(() => { })
        },

        // 批量操作
        batchHandle() {
            if (this.selectedIds.length === 0) {
                this.$message.warning('请选择要操作的订单')
                return
            }
            this.showBatch = true
        },

        // 提交批量操作
        async submitBatch() {
            try {
                if (this.batchForm.operationType === 'status') {
                    if (!this.batchForm.status) {
                        this.$message.warning('请选择状态')
                        return
                    }

                    await batchOperation({
                        ids: this.selectedIds,
                        operation: 'status',
                        status: this.batchForm.status
                    })

                    this.$message.success('批量状态修改成功')
                } else if (this.batchForm.operationType === 'delete') {
                    await deleteOrder(this.selectedIds)
                    this.$message.success('批量删除成功')
                }

                this.showBatch = false
                this.getList()
            } catch (error) {
                console.error('批量操作失败:', error)
                this.$message.error('批量操作失败')
            }
        },

        // 导出订单
        exportOrders() {
            const params = {
                ...this.searchParams,
                export: true
            }

            // 构建导出URL
            const queryString = Object.keys(params)
                .filter(key => params[key] !== null && params[key] !== undefined && params[key] !== '')
                .map(key => `${key}=${encodeURIComponent(params[key])}`)
                .join('&')

            const exportUrl = `/api/orders/export?${queryString}`

            // 创建下载链接
            const link = document.createElement('a')
            link.href = exportUrl
            link.download = `订单列表_${new Date().toISOString().split('T')[0]}.xlsx`
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link)

            this.$message.success('导出任务已开始，请稍后查看下载文件')
        },

        // 格式化价格（千分位，保留两位小数）
        formatPrice(price) {
            if (price === null || price === undefined) return '0.00'
            const num = Number(price)
            if (!isFinite(num)) return '0.00'
            return num.toLocaleString('zh-CN', {
                minimumFractionDigits: 2,
                maximumFractionDigits: 2
            })
        },

        // 格式化日期时间
        formatDateTime(dateTime) {
            if (!dateTime) return '-'
            return dateTime;
            /*const date = new Date(dateTime)
            return date.toLocaleString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit'
            })*/
        },
        // 重量 千分符
        formatWeight(weight) {
            if (weight === null || weight === undefined || weight === '') return '0'
            const num = Number(weight)
            if (!isFinite(num)) return '0'
            return num.toLocaleString('zh-CN')
        },
    }
}
</script>

<style lang="scss" scoped>
.price-text {
    color: #e6a23c;
    font-weight: 500;
}

.el-tag {
    margin-right: 5px;
}

.search-container {
    margin-bottom: 20px;
}

.el-table {
    margin-top: 20px;
}

.dialog-footer {
    text-align: right;
}
</style>
